import unittest
from random import random

from toBeTest import ToBeTest


class assert_test(unittest.TestCase):
    def test_assert(self):
        list1 = [1, 2, 3, 4, 5, 6, 7]
        list2 = list1
        # list2 = [1, 2, 3, 4, 5, 6, 7]
        try:
            self.assertIs(list1, list2, "%s与%s不属于同一对象" % (list1, list2))
        except AssertionError as e:
            print(e)

    def test_assertnone(self):
        results = ToBeTest.return_none()
        self.assertIsNone(results, "is none")
        self.assertIsNotNone(results, "is not none")

    # assertIsInstance()方法实例
    def test_assertisinstance(self):
        try:
            o = ToBeTest
            k = object
            # 断言测试对象o是k的类型
            self.assertIsInstance(o, k, "%s的类型不是%s" % (o, k))
        except AssertionError as e:
            print(e)

    # assertNotIsInstance()方法实例
    def test_assertnotisinstance(self):
        try:
            o = ToBeTest
            k = int
            # 断言测试对象o不是k的类型
            self.assertNotIsInstance(o, k, "%s 的类型是%s" % (o, k))
        except AssertionError as e:
            print(e)

            # assertRaises ()方法实例

    def test_assertraises(self):
        # 测试抛出指定的异常类型
        #assertRaises(exception)
        with self.assertRaises(TypeError) as exc:
            random.sample([1, 2, 3, 4, 5, 6], "j")
            # 打印详细的异常信息
            print(exc.exception)
            #assertRaises(exception, callable, *args, **kwds)
        try:
            self.assertRaises(ZeroDivisionError, ToBeTest.div, 3, 0)
        except ZeroDivisionError as e:
            print(e)

    # assertRaisesRegexp()方法实例
    def test_assertraisesregex(self):
        # 测试抛出指定的异常类型，并用正则表达式去匹配异常信息
        #assertRaisesRegex(exception, regexp)
        with self.assertRaisesRegex(ValueError, "literal") as exc:
            int("abc")
            # 打印详细的异常信息
            print(exc.exception)
            #assertRaisesRegex(exception, regexp, callable, *args, **kwds)
        try:
            self.assertRaisesRegex(ValueError, 'invalid literal for.*\'abc\'$', int, 'abc')
        except AssertionError as e:
            print(e)


if __name__ == "__main__":
    unittest.main()
